package com.b2c.erp.controller;


import com.b2c.entity.api.ApiResult;
import com.b2c.entity.api.ApiResultEnum;
import com.b2c.common.utils.Md5Util;
import com.b2c.common.utils.OrderNumberUtils;
import com.b2c.entity.DataRow;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PayTestController {
    Logger log = LoggerFactory.getLogger(PayTestController.class);
    @RequestMapping("/pay")
    public String pay(Model model, HttpServletRequest req) {
        return "test/pay";
    }

    @RequestMapping("/pay_result")
    public String payResult(Model model, HttpServletRequest req) {
        return "test/pay_result";
    }
    

    @ResponseBody
    @RequestMapping("/pay_sumbit")
    public ApiResult<String> reviewRefundOffline(@RequestBody DataRow data, HttpServletRequest req) {
        Double amount = data.getDouble("amount");
        String receive_name= data.getString("receive_name");
        String receive_account = data.getString("receive_account");


        String merchant_id="12002";
        String order_id=OrderNumberUtils.getOrderIdByTime();
        String transfer_type = "2";
        String passKey = "a5938ded6843fc86568deb452a5da697";
        String ifsc_code = "";
        String notify_url="";


        HashMap<String,String> params2 = new HashMap<>();
        params2.put("merchant_id", merchant_id);
        params2.put("order_id", order_id);
        params2.put("amount", amount+"");
        params2.put("receive_name", receive_name);
        params2.put("receive_account", receive_account);
        params2.put("transfer_type", transfer_type);
        // params2.put("key",passKey);
        // params2.put("ifsc_code", "");
        // params2.put("notify_url", "");

        String[] sortedKeys = params2.keySet().toArray(new String[]{});
		Arrays.sort(sortedKeys);// 排序请求参数
        StringBuilder s2 = new StringBuilder();
        for (String key : sortedKeys) {
        	s2.append(key).append("=").append(params2.get(key)).append("&");
        }
        s2.deleteCharAt(s2.length() - 1);
        s2.append("&key="+passKey);
		log.info("参与签名参数："+s2.toString());
        String sign =  Md5Util.MD5(s2.toString()).toLowerCase();
        log.info("签名："+sign);
        params2.put("sign",sign);


        StringBuffer paramsStr = new StringBuffer();
        boolean isfist = true;
        for (Map.Entry<String, String> entry : params2.entrySet()) {
            if (isfist) {
                isfist = false;
            } else {
                paramsStr.append("&");
            }
            paramsStr.append(entry.getKey()).append("=");
            String value = entry.getValue();
            paramsStr.append(value);
            // if (!StringUtils.isEmpty(value)) {
            //     paramsStr.append(URLEncoder.encode(value, "UTF-8"));
            // }
        }
        // paramsStr.append("&key="+passKey);
        log.info("最终参数："+paramsStr.toString());
        
        String url = "https://pay.3kcpay.com/api/india/withdrawal";
        try {
            HttpClient client = HttpClient.newBuilder().build();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url)).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(paramsStr.toString()))
                    .build();
                    HttpResponse<String> respone = client.send(request, HttpResponse.BodyHandlers.ofString());
                    log.info("相应结果："+respone.body());
        } catch (Exception e) {
            log.error("ExpressClient doPost exception:" + e.getMessage());
        }
       
        return new ApiResult<>(ApiResultEnum.SUCCESS.getIndex(), "SUCCESS");
    }
}
